package com.lots.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.lots.properties.AliOssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

@Slf4j
@Component
public class AliOssUtil {

    private final AliOssProperties properties;

    // 构造函数注入配置类
    public AliOssUtil(AliOssProperties properties) {
        this.properties = properties;
    }

    /**
     * 文件上传
     *
     * @param bytes      文件字节
     * @param objectName 上传到 OSS 的对象名
     * @return 文件访问 URL
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(
                properties.getEndpoint(),
                properties.getAccessKeyId(),
                properties.getAccessKeySecret()
        );

        try {
            // 上传文件
            ossClient.putObject(properties.getBucketName(), objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            log.error("OSSException: Code={}, Message={}, RequestId={}, HostId={}",
                    oe.getErrorCode(), oe.getErrorMessage(), oe.getRequestId(), oe.getHostId(), oe);
        } catch (ClientException ce) {
            log.error("ClientException: {}", ce.getMessage(), ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // 文件访问路径规则：https://BucketName.Endpoint/ObjectName
        String url = "https://" + properties.getBucketName() + "." + properties.getEndpoint() + "/" + objectName;
        log.info("文件上传到: {}", url);
        return url;
    }
}
